package study.web.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import study.domain.Constants;
import study.domain.user.User;
import study.service.user.UserService;

/**
 * 사용자 인증 성공 핸들러
 *
 * @author Barney Kim
 */
public class UserAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler
	implements AuthenticationSuccessHandler {

	@Autowired
	private UserService userService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		HttpSession session = request.getSession();
		String username = getUsername(authentication);
		User user = userService.getUser(username);
		if(user != null) {
			logger.debug("User '"+username+"' into session");
			session.setAttribute(Constants.SESSION_KEY, user);
		} else{
			logger.error("User '"+username+"' NOT FOUND");
		}
		super.onAuthenticationSuccess(request, response, authentication);
	}

	private String getUsername(Authentication authentication) {
		Object principal = authentication.getPrincipal();
		if (principal instanceof UserDetails) {
			return ((UserDetails) principal).getUsername();
		} else {
			return principal.toString();
		}
	}
}
